package com.ishow.common.utils;

import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 操作redis的静态类，需要在spring里配置，不然取不到redis的配置信息
 * 
 * @author chichi
 *
 * @param <K>
 * @param <V>
 */
public class RedisUtil<K, V> {
	private static RedisTemplate<String, Object> redisTemplate;

	private static final long timeout = 5;

	/**
	 * 添加对象到redis
	 * 
	 * @param key
	 * @param value
	 */
	public static void addValue(String key, Object value) {
		addValue(key, value, timeout);
	}

	/**
	 * 添加对象到redis
	 * 
	 * @param key
	 * @param value
	 * @param timeout
	 */
	public static void addValue(String key, Object value, long timeout) {
		redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
		// redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
	}

	/**
	 * 刷新key的过期时间
	 * 
	 * @param key
	 * @param timeout
	 */
	public static void expire(String key, long timeout) {
		redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
	}

	public static Object getValue(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	public static void remove(String key) {
		redisTemplate.delete(key);
	}

	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		RedisUtil.redisTemplate = redisTemplate;
	}
}
